﻿using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System;

public class Joystick : ScrollRect
{
	private Vector2 m_ForceVector;
	private bool m_IsonDragBegin;
	protected float m_Radius;
	private event Action m_onDragBegin;
	private event Action m_onDrag;
	private event Action m_onDragEnd;

	private static Joystick m_Singleton;

	/// <summary>
	/// 获取Joystick的实例
	/// </summary>
	public static Joystick Instance { get { return m_Singleton; } }

	protected override void Awake()
	{
		if (m_Singleton == null)
		{
			m_Singleton = this.gameObject.GetComponent<Joystick>();
		}
	}

	// 摇杆输出的方向向量
	public Vector2 ForceVector
	{
		get
		{
			return m_ForceVector;
		}
		private set { }
	}

	/// <summary>
	/// 开始触发摇杆
	/// </summary>
	public Action OnDragBegin { set { m_onDragBegin = value; } }

	/// <summary>
	/// 持续触发中
	/// </summary>
	public Action OnSustainDrag { set { m_onDrag = value; } }

	/// <summary>
	/// 停止触发摇杆
	/// </summary>
	public Action OnDragEnd { set { m_onDragEnd = value; } }

	protected override void Start()
	{
		base.Start();
		m_ForceVector = Vector2.zero;
		m_Radius = ((transform as RectTransform).sizeDelta.x * 0.5f) * 0.8f; // 计算摇杆块的半径
																			 //m_Radius = 50f;
	}

	public override void OnDrag(UnityEngine.EventSystems.PointerEventData eventData)
	{
		base.OnDrag(eventData);
		var contentPostion = this.content.anchoredPosition;
		if (contentPostion.magnitude > m_Radius)
		{
			contentPostion = contentPostion.normalized * m_Radius;
			SetContentAnchoredPosition(contentPostion);
		}
		m_ForceVector = contentPostion.normalized;

		if (m_onDrag != null && m_IsonDragBegin)
		{
			m_onDrag.Invoke();
		}

		if (!m_IsonDragBegin)
		{
			if (m_onDragBegin != null)
			{
				m_onDragBegin.Invoke();
			}
			m_IsonDragBegin = true;
		}

	}

	public override void OnEndDrag(PointerEventData eventData)
	{
		base.OnEndDrag(eventData);
		m_ForceVector = Vector2.zero;
		if (m_onDragEnd != null)
		{
			m_onDragEnd.Invoke();
		}
		m_IsonDragBegin = false;
	}
}

